import Block from 'src/components/Block'
import s from './index.module.scss'
import r from 'src/reset.module.scss'

import {atom, useAtom} from 'helux'
import Button from 'src/components/Button'

const [shareState] = atom({ a: 100, b: {b1: 1} })

const td = {
  title: '搜索案例五：防抖',
  desc: '自定义hook，由于输入过程中，input 的 onchange 事件会高频率触发，如果每一次改变都要去响应对应的逻辑有可能会造成性能问题，因此，我们采用防抖的策略，在输入结束之后自动开始搜索'
}

export default function DemoOneNormal() {
  const [state, setState] = useAtom(shareState)

  const change = () => setState((df) => {df.a = 20})

  return (
    <Block className={s.container} title={td.title} desc={td.desc}>
      <div className={r.flex}>{state.a}</div>
      <Button onClick={change}>change</Button>
    </Block>
  )
}

const customerData = [
  { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
  { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" },
];

let db: IDBDatabase
let store: IDBObjectStore

const request = window.indexedDB.open('region', 3)
request.onupgradeneeded = (event) => {
  let target: IDBOpenDBRequest = event.target as IDBOpenDBRequest
  db = target.result

  let store = db.createObjectStore('customers', {keyPath: 'ssn'})

  store.createIndex('name', 'name', {unique: false})
  store.createIndex('email', 'email', {unique: true})

  store.transaction.oncomplete = (event) => {
    const customerStore = db.transaction('customers', 'readwrite').objectStore('customers')
    customerData.forEach(customer => {
      customerStore.add(customer)
    })
  }
}
request.onerror = () => {
  console.error('数据库发生了异常')
}
request.onsuccess = (event) => {
  console.log('数据库 regin 连接成功')
  const target: IDBOpenDBRequest = event.target as IDBOpenDBRequest
  db = target.result
  store = db.transaction('customers', 'readwrite').objectStore('customers')
  console.log('数据表 customers 连接成功')
}

setTimeout(() => {
  console.log('插入一条数据')
  store = db.transaction('customers', 'readwrite').objectStore('customers')
  const request = store.add({ ssn: '777-77-7777', name: 'Tom', age: 10, email: 'xxx@home.org' })
  request.onsuccess = (event) => {
    console.log(event.target)
  }
  request.onerror = (event) => {
    const target: IDBRequest = event.target as IDBRequest
    console.error(target.error)
  }
}, 2000)
